const { verify, getToken } = require('./token')
const mongoose = require('mongoose')
const Log = mongoose.model('Log')

const logMiddleware = async (ctx, next) => {
    const startTime = Date.now()
    await next()
    let payload = {}
    try {
        payload = await verify(getToken(ctx))
    } catch (e) {
        payload = {
            username: '未知用户',
            id: ""
        }
    }
    // console.log('打印ctx',ctx);
    const url = ctx.url
    const method = ctx.method
    const status = ctx.response.status
    console.log('url', url, 'payload', payload);
   
    // let responseBody = ""
    // if (typeof ctx.body == 'string') {
    //     responseBody = ctx.body
    // } else {
    //     try {
    //         responseBody = JSON.stringify(ctx.body)
    //     } catch {
    //         responseBody = ""
    //     }
    // }
    const log = new Log({
        user: {
            account: payload.username,
            id: payload._id
        },
        request: {
            url: url,
            responseBody: '',
            method,
            status
        }
    })

    // console.log('打印log.user', log.user);
    // console.log('打印存储的log', log);
    const endTime = Date.now()
    await log.save()
}

module.exports = {
    logMiddleware
}